<template>
	<view class="finish">
		<template>
			<view :prop="echarts" :change:prop="html2canvas.initEchart"></view>
		</template>
		<template v-if="detail">
			<view class="text-center f-base m-b-15 des-color"> {{detail.sleep_text}}</view>
			<view class="text-center bold title m-b-20" v-if="detail.power">获得了 <text class="green p-row-5">{{detail.power}}</text> 能量</view>
			<view class="report">
				<u--image class="star star1" height="28"
				src="https://cdn3.relaverse.cn/appfile/sleep-finish-star1.png" width="28"
					></u--image>
				<u--image class="star star2" src="https://cdn3.relaverse.cn/appfile/sleep-finish-star2.png" width="44"
					height="44"></u--image>
				<view class="flex-no-horizontal between">
					<view>
						<view class="flex-no-horizontal flex-end m-b-10">
							<view class="score">{{detail.score}}</view>
							
							<u--image style="transform: translateY(-10px);"
								:src="detail.sleep_level.icon" width="62" height="15"
								mode="widthFix"></u--image>
						</view>
						<u--image src="https://cdn3.relaverse.cn/appfile/sleep-finish-get.png" width="86" height="16"
							mode="widthFix"></u--image>
					</view>
					<u--image :src="detail.sleep_icon" width="101" height="101">
					</u--image>
				</view>
				<view class=" m-b-20 my-echart m-t-10">
					<view id="main" style="width: 240px;height: 180px;"></view>
				</view>
				<view class="f-10 white m-b-20" v-html="detail.sleep_suggest">
					
				</view>
				<u-line dashed color="rgba(255,255,255,0.5)"></u-line>
				<view class="m-t-30 flex-no-horizontal f-xxs center" style="color: rgba(255,255,255,0.5);">
					点击查看完整分析
					<u-icon name="arrow-right" color="rgba(255,255,255,0.5)" size="12"></u-icon>
				</view>
			</view>
			<view class="flex-no-horizontal between btn-group">
				<view class="sleep-tip-button">
					<u-button color="rgba(227, 231, 255, 0.2)" shape="circle"
					@click="toSleep">
						<text class="bold f-base">返回首页</text>
					</u-button>
				</view>
				<view @click="html2canvas.showPoster" class="sleep-tip-button">
					<u-button shape="circle"
						color="linear-gradient(0deg, #00B0C0 0%, #00CBB1 100%)">
						<text class="bold f-base">打卡分享</text>
					</u-button>
				</view>
			</view>
		</template>
		<view class="bottom flex-no-horizontal f-base between"
		v-if="detail"
		@click="html2canvas.showAcity">
			{{detail.sleep_activity.name}}
			<u-button color="rgba(255, 255, 255, 0.2)"
			shape="circle" class="bottom-btn">
				<text class="f-xxs">邀请好友</text>
			</u-button>
		</view>
		<!-- 早睡活动 -->
		<u-popup :show="isShowActity" @close="cancelShowPoster"
		overlayOpacity="1" safeAreaInsetBottom mode="center"
		bgColor="#000000">
			<view class="poster" v-if="share">
				<view class="create" id="create" v-show="!base64">
					<view class="flex-no-horizontal center create-avatar">
						<img :src="user.avatar"
						style="height: 64px;width: 64px;border-radius: 50%;"
						/>
					</view>
					<view style="position: relative;margin-top: -32px;">
						<img src="https://cdn3.relaverse.cn/appfile/sleep-finish-fengxi.png"
						class="create-bg"/>
						<view style="position: relative;z-index: 2;padding-top: 90rpx;">
							<view class="flex-no-horizontal center m-b-5">
								<view class="bold f-15 white m-r-5">{{user.nickname}}</view>
								<img :src="share.sleep_level.icon"
									style="height: 15px;width: 62px;display: block;" mode="widthFix"></img>
							</view>
							<view class="text-center f-10 white m-b-20" style="opacity: 0.7;">
								{{share.finished_text}}
							</view>
							<view class="flex-no-horizontal center">
								<img :src="share.share_img" width="183"
									style="height: 183px;width: 183px;border-radius: 10px;" class="m-b-20"></img>
							</view>
							<view class="text-center f-xxs white m-b-10">{{share.share_text}}</view>
							<view class="flex-no-horizontal center m-b-10">
								<img :src="share.share_text_img"
								style="height: 52px;width: 206px;"
									mode="heightFix"></img>
							</view>
							<view class="create-bottom flex-no-horizontal between">
								<view class="white f-xs" v-html="share.invite_text">
								</view>
								
								
								<view class="my-qr-code">
									<img :src="share.qr_code" style="width: 50px;height: 50px;"/>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="real-poster">
					<img :src="base64" width="100%" height="100%" mode="widthFix"></img>
				</view>
				<view class="share">
					<view class="flex-no-horizontal between">
						<view class="share-item" @click="shareSceneSession">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="weixin-fill" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">微信</view>
						</view>
						<view class="share-item" @click="shareTimeline">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="moments" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">朋友圈</view>
						</view>
						<view class="share-item" @click="save">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="download" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">保存到手机</view>
						</view>
						<view class="share-item" @click="copy">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u--image src="https://cdn3.relaverse.cn/appfile/sleep-poster-copy.png" width="22"
									height="22"></u--image>
							</view>
							<view class="text-center share-text f-10">复制邀请码</view>
						</view>
					</view>
					<u-divider lineColor="rgba(211, 255, 241, 0.2)" class="m-t-20 m-b-20"></u-divider>
					<view class="text-center f-base white"
					@click="cancelShowPoster"
					style="opacity: 0.5;">取消</view>
				</view>
			</view>
		</u-popup>
		<!-- 分享打卡 -->
		<u-popup :show="isShowPoster" @close="cancelShowPoster"
		overlayOpacity="1" safeAreaInsetBottom mode="center"
		bgColor="#000000">
			<view class="poster poster2" v-if="share">
				<view class="create" id="create" v-show="!base64">
					<view class="flex-no-horizontal center create-avatar">
						<view class="m-b-5 z-index">
							{{day}}
						</view>
						<view class="z-index">
							星期{{weekday}}
						</view>
						<img class="create-avatar-bg"
						src="https://cdn3.relaverse.cn/appfile/sleep-tag.png"
						style="height: 57px;width: 42px;"
						/>
					</view>
					<view class="draw">
						<img src="https://cdn3.relaverse.cn/appfile/sleep-poster2-bg.png"
						class="create-bg"/>
						<view class="draw-content z-index">
							<view>
								<img src="https://cdn3.relaverse.cn/appfile/sleep-logo-green.png"
								style="width: 34px;height: 34px;"/>
							</view>
							<!-- <view class="draw-content-title text-center">
								睡眠打卡 <text class="p-row-5" style="color: #FFF2D4;">1</text> 天  我的睡眠得分
							</view> -->
							<view v-html="result.share_text" class="draw-content-title text-center"></view>
							<view class="text-center draw-content-scroe">
								{{result.score}}
							</view>
							<view class="flex-no-horizontal center m-b-30">
								<img :src="result.sleep_level.icon"
									style="height: 22px;width: 85px;display: block;" mode="widthFix"></img>
							</view>
							<view class="flex-no-horizontal center">
								<img :src="result.share_image" mode="widthFix"
									style="height: 100%;width: 190px;"></img>
							</view>
							<view class="create-bottom flex-no-horizontal between">
								<view class="white f-xs">
									<view class="flex-no-horizontal m-b-10">
										<view class="m-r-10">
											<img :src="user.avatar"
											style="width: 21px;height: 21px;border-radius: 50%;display: block;"/>
										</view>
										<text class="f-base" style="color: rgba(138, 255, 234, 0.7);">{{user.nickname}}</text>
									</view>
									<view class="f-xxs" style="color: rgba(138, 255, 234, 0.5);">快来和我一起体验睡眠宫殿吧</view>
								</view>
								<view class="my-qr-code">
									<img :src="result.qs_code" style="height: 50px;height: 50px;border-radius: 3px;"/>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="real-poster">
					<img :src="base64" width="100%" height="100%" mode="widthFix"></img>
				</view>
				<view class="share">
					<view class="flex-no-horizontal between">
						<view class="share-item" @click="shareSceneSession">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="weixin-fill" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">微信</view>
						</view>
						<view class="share-item" @click="shareTimeline">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="moments" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">朋友圈</view>
						</view>
						<view class="share-item" @click="save">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u-icon name="download" color="white" size="22"></u-icon>
							</view>
							<view class="text-center share-text f-10">保存到手机</view>
						</view>
						<view class="share-item" @click="copy">
							<view class="share-icon flex-no-horizontal center m-b-10">
								<u--image src="https://cdn3.relaverse.cn/appfile/sleep-poster-copy.png" width="22"
									height="22"></u--image>
							</view>
							<view class="text-center share-text f-10">复制邀请码</view>
						</view>
					</view>
					<u-divider lineColor="rgba(211, 255, 241, 0.2)" class="m-t-20 m-b-20"></u-divider>
					<view class="text-center f-base white"
					@click="cancelShowPoster"
					style="opacity: 0.5;">取消</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		shareFriend,
		shareMoment,
		judgeIosPermissionPhotoLibrary
	} from '../../utility/share.js'
	import {endSleep,getShare,getResultShare as getResultShareApi} from '../../api/sleep.js'
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				isShowPoster: false,
				base64: null,
				detail: null,
				result: null,
				echarts: null,
				sleepId: 0,
				share: null,
				qrCodeImg: '',
				isShowActity: false,
				day:null,
				weekday: null,
			}
		},
		computed: {
			...mapState({
				user: state => state.userInfo
			})
		},
		onLoad(option) {
			this.sleepId = option.sleepId
			this.getShareConfig()
			this.getResultShare(this.sleepId)
			const now = new Date()
			this.day = `${now.getMonth() + 1}/${now.getDate()}`
			switch (now.getDay()){
				case 1:
					this.weekday = '一'
					break;
				case 2:
					this.weekday = '二'
					break;
				case 3:
					this.weekday = '三'
					break;
				case 4:
					this.weekday = '四'
					break;
				case 5:
					this.weekday = '五'
					break;
				case 6:
					this.weekday = '六'
					break;
				default:
					this.weekday = '日'
					break;
			}
		},
		async onReady() {
			try{
				await this.getNetwork()
				this.finish(this.sleepId)
				
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
			uni.onNetworkStatusChange(this.getNetStatus)
		},
		onBackPress() {
			uni.offNetworkStatusChange(this.getNetStatus)
		},
		methods: {
			getNetwork() {
				return new Promise((resolve,reject) => {
					uni.getNetworkType({
						success: (res) => {
							if (res.networkType == 'none') {
								uni.showToast({
									title: '检查网络是否连接',
									duration: 2000,
									icon: 'none'
								})
								reject(false)
							} else {
								resolve(true)
							}
						}
					})
				})
			},
			getNetStatus(res) {
				console.log(res.isConnected)
				if (!res.isConnected) {
					uni.showToast({
						title: '检查网络是否连接',
						duration: 2000,
						icon: 'none'
					})
				} else if (!this.detail && res.isConnected) {
					this.finish(this.sleepId)
					this.getShareConfig()
					this.getResultShare(this.sleepId)
				}
			},
			async getShareConfig() {
				try{
					const res = await getShare()
					this.share = res.data
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			async getResultShare(id) {
				try{
					const res = await getResultShareApi({sleep_id: id})
					this.result = res.data
				}catch(e){
					//TODO handle the exception
				}
			},
			copy() {
				uni.setClipboardData({
					data: this.$store.state.userInfo.code,
					success() {
						uni.showToast({
							title: '已复制到剪切板',
							icon: 'none'
						})
					}
				})
			},
			toSleep() {
				uni.offNetworkStatusChange(this.getNetStatus)
				uni.navigateBack()
			},
			closePoster() {
				this.isShowPoster = false
				this.isShowActity = false
				this.base64 = null
			},
			showLoadingAcity() {
				this.isShowActity = true
				uni.showLoading({
					title: '生成海报中...'
				})
				
			},
			showLoadingPoster() {
				this.isShowPoster = true
				uni.showLoading({
					title: '生成海报中...'
				})
			},
			renderFinish(option) {
				this.base64 = option.path
				uni.hideLoading()
			},
			hideLoading() {
				uni.hideLoading()
			},
			shareSceneSession() {
				shareFriend(this.base64)
			},
			shareTimeline() {
				shareMoment(this.base64)
			},
			save() {
				judgeIosPermissionPhotoLibrary(this.base64)
			},
			async finish(id) {
				uni.showLoading({})
				try{
					const res = await endSleep({sleep_id: id})
					this.detail = res.data
					this.echarts = this.detail.sleep_statistics
					uni.$emit('finish')
					uni.removeStorageSync('sleepId')
					uni.hideLoading()
				}catch(e){
					console.log('err',e)
					uni.hideLoading()
					//TODO handle the exception
				}
			},
			cancelShowPoster() {
				this.isShowPoster = false
				this.isShowActity = false
				this.base64 = null
			}
		}
	}
</script>


<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas'
	// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
	import * as echarts from 'echarts/core';
	// 引入柱状图图表，图表后缀都为 Chart
	import {
		BarChart
	} from 'echarts/charts';
	// 引入提示框，标题，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
	import {
		TitleComponent,
		TooltipComponent,
		GridComponent,
		DatasetComponent,
		TransformComponent
	} from 'echarts/components';
	// 标签自动布局，全局过渡动画等特性
	import {
		LabelLayout,
		UniversalTransition
	} from 'echarts/features';
	// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
	import {
		CanvasRenderer
	} from 'echarts/renderers';

	// 注册必须的组件
	echarts.use([
		TitleComponent,
		TooltipComponent,
		GridComponent,
		DatasetComponent,
		TransformComponent,
		BarChart,
		LabelLayout,
		UniversalTransition,
		CanvasRenderer
	]);

	export default {
		methods: {
			showAcity() {
				this.$ownerInstance.callMethod('showLoadingAcity', true)
				this.createPoster()
			},
			showPoster() {
				this.$ownerInstance.callMethod('showLoadingPoster', true)
				this.createPoster()
			},
			// 分享海报
			createPoster() {
				setTimeout(async () => {
					try {
						const dom = document.getElementById('create')
						console.log(dom)
						const canvas = await html2canvas(dom, {
							// width: dom.offsetWidth - 1, //设置canvas尺寸与所截图尺寸相同，防止白边
							// height: dom.offsetHeight - 2, //防止白边
							logging: true,
							useCORS: true,
							scale: 3,
							scrollY: 0,
							backgroundColor: "#000000"
						})
						const base64 = canvas.toDataURL('image/jpeg', 1);
						this.$ownerInstance.callMethod('renderFinish', {
							path: base64
						})
					} catch (e) {
						this.$ownerInstance.callMethod('hideLoading', true)
						console.log(JSON.stringify(e) ,e)
					}
				}, 4000)
			},
			// 绘制睡眠报告
			initEchart(newValue,oldValue) {
				const myChart = echarts.init(document.getElementById('main'));
				// 绘制图表
				myChart.setOption({
					tooltip: {
						show: true,
						trigger: 'item'
					},
					title: {
						subtext: "单位（小时）",
						left: 0,
						top: -5,
						subtextStyle: {
							fontSize: 10,
							align: 'left',
							color: 'white'
						}
					},
					xAxis: {
						data: ['总时长', '入睡时间', '熟睡', '浅睡'],
						axisLabel: {
							color: '#F9FFFF',
							fontSize: 10
						},
						axisLine: {
							lineStyle: {
								color: 'rgba(255,255,255,0.1)',
							},
						}
					},
					yAxis: {
						axisLabel: {
							color: '#F9FFFF',
							fontSize: 10
						},
						splitLine: {
							lineStyle: {
								color: 'rgba(255,255,255,0.1)',
							}
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: 'rgba(255,255,255,0.1)',
							},
						}
					},
					series: [{
						name: '时长',
						type: 'bar',
						data: [{
								value: newValue.total,
								itemStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#6BB1FF'
									}, {
										offset: 1,
										color: '#9ECBFF'
									}])
								}
							},
							{
								value: newValue.sleep_time,
								itemStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#956BFF'
									}, {
										offset: 1,
										color: '#BA9EFF'
									}])
								}
							},
							{
								value: newValue.deep_sleep,
								itemStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#6BFFD0'
									}, {
										offset: 1,
										color: '#9EFFE0'
									}])
								}
							},
							{
								value: newValue.light_sleep,
								itemStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 0,
										color: '#6BECFF'
									}, {
										offset: 1,
										color: '#9EF2FF'
									}])
								}
							}
						],
						label: {
							show: true,
							position: 'top',
							color: 'white',
							fontSize: 10
						},
					}],
					grid: {
						top: '40px',
						left: '30px',
						bottom: '25px',
						right: '-5px'
					}
				})
			}
		},
	}
</script>

<style scoped lang="scss">
	.finish {
		height: 100vh;
		box-sizing: border-box;
		background-color: #000205;
		position: relative;
		padding-top: 150rpx;
		.create-qrcode{
			position: absolute;
			top: -100px;
		}
		.white {
			color: white;
		}

		.des-color {
			color: #B4BAD5;
		}

		.title {
			color: #FFFFFF;
			font-size: 20px;

			.green {
				color: #00FDDD;
			}
		}

		.flex-end {
			align-items: flex-end;
		}

		.center {
			justify-content: center;
		}

		.report {
			width: 613rpx;
			box-sizing: border-box;
			margin: auto;
			position: relative;
			background: url(https://cdn3.relaverse.cn/appfile/sleep-finish-fengxi.png) no-repeat;
			background-size: 100% 100%;
			padding: 40rpx 40rpx 40rpx 65rpx;

			.star {
				position: absolute;
			}

			.star1 {
				top: -20px;
				left: -20px;
			}

			.star2 {
				top: -45px;
				right: -10px;
			}

			.score {
				font-size: 53px;
				font-family: Source Han Sans CN;
				font-weight: bold;
				font-style: italic;
				color: #FEFEFE;
				line-height: 60px;
				text-shadow: 0px 11px 23px #00C09C;

				background: linear-gradient(0deg, #00FFB4 0%, #00FCFF 100%);
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				padding-right: 20rpx;
			}

			.my-echart {
				background: rgba(206, 214, 255, 0.15);
				border-radius: 20rpx;
			}
		}

		.btn-group {
			padding: 60rpx;

			.sleep-tip-button {
				width: 45%;
				height: 93rpx;
			}
		}

		.bottom {
			color: white;
			padding: 34rpx 40rpx;
			position: absolute;
			bottom: 20rpx;
			width: 690rpx;
			left: calc(50% - 345rpx);
			background: url(https://cdn3.relaverse.cn/appfile/sleep-finish-bottom.png) no-repeat;
			background-size: 100% 100%;
			box-sizing: border-box;

			.bottom-btn {
				width: 165rpx;
				height: 63rpx;
				margin: 0;
			}
		}

		.poster {
			height: 100vh;
			position: relative;
			width: 100vw;

			.create {
				width: 308px;
				margin: auto;
				box-sizing: border-box;
				position: relative;
				background-color: #000205;
				padding: 20rpx 0;
				margin-top: 100px;
				.create-bg{
					position: absolute;
					top: 0;
					height: 100%;
					left: 0;
					width: 100%;
				}
				.create-avatar {
					position: relative;
					z-index: 2;
				}

				.create-bottom {
					background-color: rgba(255, 255, 255, 0.05);
					padding: 30rpx 40rpx;
					border-radius: 0 0 35rpx 35rpx;
					.my-qr-code{
						// height: 47px;
						// width: 47px;
						// padding: 3px;
						// background-color: white;
					}
				}
			}
			
			.real-poster{
				width: 320px;
				position: absolute;
				z-index: 2;
				left: 50%;
				transform: translate(-50%,-58%);
				top: 50%;
			}

			.share {
				width: 100vw;
				box-sizing: border-box;
				padding: 80rpx 40rpx 40rpx;
				position: absolute;
				bottom: 30rpx;
				left: 0;

				.share-item {
					display: flex;
					flex-direction: column;
					align-items: center;

					.share-icon {
						background-color: rgba(208, 255, 253, .1);
						width: 88rpx;
						height: 88rpx;
						border-radius: 50%;
					}

					.share-text {
						opacity: 0.6;
						color: #FFFFFF;
					}
				}
			}
		}
		
		.poster2{
			.create{
				box-sizing: content-box;
				padding: 0;
				.z-index{
					position: relative;
					z-index: 1;
				}
				.create-avatar{
					position: absolute;
					top: -3px;
					right: 18px;
					color: rgba(204, 252, 255, 0.7);
					font-size: 11px;
					justify-content: center;
					width: 42px;
					height: 57px;
					flex-direction: column;
					.create-avatar-bg{
						position: absolute;
						width: 100%;
						height: 100%;
						top: 0;
						left: 0;
					}
				}
				.draw{
					position: relative;
					.draw-content{
						padding: 40rpx;
						.draw-content-title{
							color: #8AFFEA;
							opacity: 0.7;
							font-size: 13px;
							margin-top: 70rpx;
						}
						.draw-content-scroe{
							font-weight: bold;
							font-style: italic;
							color: rgba(0,255,174,0.7);
							text-shadow: 0px 0px 5px #00C09C;
							font-size: 61px;
							// background: linear-gradient(0deg, #00FFAE 0%, #00FCFF 100%);
							// -webkit-background-clip: text;
							// -webkit-text-fill-color: transparent;
						}
						.create-bottom{
							background-color: transparent;
							padding: 0;
						}
					}
				}
			}
		}
	}
</style>
